/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets;

import beans.Customer;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import store.*;

/**
 * AddToCart handles the intermediary position between CheckOut and Shopping.
 * This class adds
 * items to the Customer bean's cartItems list for later processing.
 * @author Alex
 */
@WebServlet(name = "AddToCart", urlPatterns = {"/AddToCart"})
public class AddToCart extends HttpServlet {

    /**
     * doPost - This takes the user's request packet, and interprets it.
     * We use it to get our purchased item values.
     * @param req Client's request packet.
     * @param res Servlet's generated response packet.
     * @throws ServletException
     * @throws IOException 
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        HttpSession session = req.getSession();
        
        Customer customerBean =
                (Customer) session.getAttribute("customerBean");
        
        Enumeration<String> param = req.getParameterNames();
        
        int invCode = 0;
        float quantity = 0;
        String item = param.nextElement();
        
        try {
            while (param.hasMoreElements()) {                
                invCode = Integer.parseInt(item);
                quantity = Integer.parseInt(req.getParameter(item));
                
                if (quantity != 0) {
                    Customer.addToCart(invCode, quantity);
                }
                item = param.nextElement();
            }
            
            String itemNumberString = req.getParameter("itemNumber");
            res.sendRedirect(getInitParameter("redirectPage") + "?itemNumber="
                    + itemNumberString);

        } catch (NumberFormatException nfe) {
              // To use a JSP page for errors, need to set these TWO attributes
              req.setAttribute("javax.servlet.jsp.jspException", nfe);
              req.setAttribute("javax.servlet.error.status_code",
                      new Integer(0));

              ShopItem shopItem = ShopInventory.getShopItem(invCode);
              req.setAttribute("errorItem", shopItem.getName());
              RequestDispatcher rd = req.getRequestDispatcher(
                      getInitParameter("numberErrorPage"));
              rd.forward(req, res);
        }

    }
    
    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /*
             * TODO output your page here. You may use following sample code.
             */
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet AddToCart</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet AddToCart at " + request.getContextPath()
                    + "</h1>");
            out.println("</body>");
            out.println("</html>");
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
